import React, { useEffect, useRef, useState } from 'react'
import style from './compoments/style.module.css'
import { Button, Input, Form } from "antd"
function Useradd() {


  const emoj = ['😅']



  const ref = useRef(null)
  const sollyref = useRef()
  const user_id = 'ok'
  const [arr, setArr] = useState([])
  const [form] = Form.useForm()
  const lt = () => {
    ref.current = new WebSocket(`ws://81.70.224.2:8003/koa/ws?user_id=${user_id}&server_id=9000`)
    ref.current.onopen = () => {
      ref.current.send(JSON.stringify({ "type": "getChatList" }))
    }

    ref.current.onmessage = (e) => {
      console.log(e);
      const data = JSON.parse(e.data)
      if (data.type === 'getChatList') {
        setArr(data.data)
        setTimeout(() => {
          sollyref.current.scrollTop = 99999
          form.resetFields()
        }, 1)
      }
      else if (data.type === 'addMessage') {
        ref.current.send(JSON.stringify({ "type": "getChatList" }))
      }
    }
  }



  useEffect(() => {
    lt()
  }, [])


  const onfinish = (values) => {
    if (!values.text) {
      alert('不能空')

      return
    }
    ref.current.send(JSON.stringify({ type: "addMessage", data: { message: values.text, type: 'text' } }))

  }

  const em = (value) => {
    ref.current.send(JSON.stringify({ type: "addMessage", data: { message: value, type: 'text' } }))
  }

  return (
    <div className={style.box}>
      <div className={style.heart} ref={sollyref}>
        {
          arr.map((item) => {
            return (
              <div className={user_id === item.user_id ? style.list1 : style.list2}>
                <img src={user_id === item.user_id ? item.user_avatar : item.other_avatar} alt="" />
                <p>{item.message}</p>
              </div>
            )
          })
        }
      </div>

      <div>
        <Form onFinish={onfinish} form={form}>
          <Form.Item name='text' >
            <Input></Input>
          </Form.Item>

          <Form.Item>
            <Button htmlType='submit'>发送</Button>
          </Form.Item>

        </Form>



        <div>
          {
            emoj.map((item, index) => {
              return (
                <span key={index} onClick={() => { em(item) }}>
                  {item}
                </span>
              )

            })
          }
        </div>

      </div>


    </div>
  )
}

export default Useradd
